package com.jiot.plugin.tio;

import java.util.Objects;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.intf.Packet;
import org.tio.core.ChannelContext;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

public class MyWsMsgHandler extends BaseWebSocket implements IWsMsgHandler {
	private static Logger log = LoggerFactory.getLogger(MyWsMsgHandler.class);

	public static final MyWsMsgHandler me = new MyWsMsgHandler();

	private MyWsMsgHandler() {
		
	}

	/**
	 * 握手时走这个方法，业务可以在这里获取cookie，request参数等
	 */
	@Override
	public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
//		String clientip = request.getClientIp();
		String password = request.getHeader("password");
		String account = request.getHeader("account");
		if(StrUtil.isNotBlank(password) && StrUtil.isNotBlank(account)) {
			//User user = Redis.use(CacheConstant.appUser).get(account);//获取缓存用户
//			if(BeanUtil.isNotEmpty(user)) {
//				String privateKey = user.getPrivateKey();
//				byte[] decodedData = RSACoder.decryptByPrivateKey(password, privateKey);
//				String outputStr = new String(decodedData);
//				if(StrUtil.equals(user.getPassword(), outputStr)) {//绑定
//					Tio.bindUser(channelContext, user.getId()+"");
//		        }
//	        }
		}
		return httpResponse;
	}

	/** 
	 * 客户端连上后,服务器首次发消息
	 */
	@Override
	public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
		int count = Tio.getAll(channelContext.tioConfig).getObj().size();
//		WebSocketSendEventVO WebSocketSendEventVO = new WebSocketSendEventVO();
//		WebSocketSendEventVO.setEventType("ContextCount");
//		WebSocketSendEventVO.setContextCount(count);
		WsResponse wsResponse = WsResponse.fromText(JSONUtil.toJsonStr(11111), "utf-8");
		Tio.sendToAll(channelContext.tioConfig, wsResponse);
	}

	/**
	 * 字节消息（binaryType = arraybuffer）过来后会走这个方法
	 */
	@Override
	public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		System.out.println(bytes);
		return null;
	}

	/**
	 * 当客户端发close flag时，会走这个方法
	 */
	@Override
	public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
		Tio.remove(channelContext, "receive close flag");
		return null;
	}

	/*
	 * 字符消息（binaryType = blob）过来后会走这个方法
	 * {"eventType":xxx,...}
	 */
	@Override
	public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
		System.out.println(text);
		if(!JSONUtil.isJsonObj(text)) {
			return null;
		}
//		WebSocketEventVO wsEvent = JSONUtil.toBean(text, WebSocketEventVO.class);
//		if(StrUtil.equals(wsEvent.getEventType(), "heartbeat") ) {
//			return null;
//		}else {
			return null;
//		}
	}
	
	
	/**
	 * 发送开关状态
	 */
	public static void sendSwitch(Packet wsResponse,String userId) {
		Tio.sendToUser(TioWebsocketStarterPlugin.serverTioConfig, userId, wsResponse);
	}
	
	/**
	 * 发送实时数据
	 */
	public static void sendHeartbeat(Packet wsResponse,String userId) {
//		Tio.sendToUser(TioWebsocketStarterPlugin.serverTioConfig, userId, wsResponse);
		Tio.sendToAll(TioWebsocketStarterPlugin.serverTioConfig, wsResponse);
	}
	
	/**
	 * 发送报警数据
	 */
	public static void sendAlarm(Packet wsResponse,String userId) {
		Tio.sendToUser(TioWebsocketStarterPlugin.serverTioConfig, userId, wsResponse);
	}

}

